package cn.tedu.egweibo6.base.exception;

import cn.tedu.egweibo6.base.response.JsonResult;
import cn.tedu.egweibo6.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:{}",data);

        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:{}",data);

        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    @ExceptionHandler
    public JsonResult doHandle(HttpMessageNotReadableException ex){
        String data = "无法处理请求体的特定格式";
        log.error("HttpMessageNotReadableException:{}",data);

        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

//    @ExceptionHandler
//    public JsonResult doHandleThrowable(Throwable ex){
//        String data = ex.getMessage();
//        log.error("Throwable:{}",data);
//
//        return new JsonResult(StatusCode.OPERATION_FAILED ,data);
//    }

}
